package cn.school.job.attendance;

import cn.school.attendance.dormitory.dao.DormitoryAttendanceMapper;
import cn.school.attendance.dormitory.vo.StudentAttendanceVO;
import cn.school.common.utils.Threads;
import cn.school.sys.dao.SysConfigDao;
import cn.school.sys.entity.SysConfig;
import cn.school.wechat.utils.WeChatParamUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: lx
 * @date: 2024/3/15 16:34
 * @description: 学生异常考勤通知班主任
 */
@Slf4j
public class StudentAttendanceNoticeClassTeacher extends QuartzJobBean {

    @Autowired
    DormitoryAttendanceMapper attendanceMapper;
    @Resource
    SysConfigDao sysConfigDao;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today = format.format(new Date());
        //查询系统参数表中拥有考勤通知参数的且值为1的数据
        LambdaQueryWrapper<SysConfig> querySysConfigByKeyAndValueWrapper = new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getParamKey, "sys.job.attendance.studentAttendanceNotification")
                .eq(SysConfig::getParamValue, 1);
        //提取集合中的租户id
        List<String> tenantList = sysConfigDao.selectList(querySysConfigByKeyAndValueWrapper).stream().map(SysConfig::getTenantId).collect(Collectors.toList());
        //根据当前日和和租户ID查询全部缺寝名单
        List<StudentAttendanceVO> allAbsenceStudentList;
        if (tenantList.size() != 0) {
            allAbsenceStudentList = attendanceMapper.getAllAbsenceStuList(today, tenantList);
            for (StudentAttendanceVO studentAttendanceVO : allAbsenceStudentList) {
                if (StringUtils.isNotBlank(studentAttendanceVO.getOfficialOpenId())) {
                    //生成消息模板
                    Map<String, Object> message = WeChatParamUtil.absenceStuNtClsTeacherParam(
                            studentAttendanceVO.getStudentName(), studentAttendanceVO.getClassName(), "未归寝");
                    try {

                        Threads.sleep(2000);
                    } catch (Exception e) {
                        log.error("发送考勤异常通知班主任消息失败：" + e.getMessage());
                        continue;
                    }
                }
            }
        }
    }
}
